package com.liang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liang.common.lang.FunctionUtil;
import com.liang.entity.CNotice;
import com.liang.entity.CUser;
import com.liang.mapper.CUserMapper;
import com.liang.service.CUserDetailService;
import com.liang.service.CUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 李昂
 * @since 2020-11-30
 */
@Service
@CacheConfig(cacheNames = "CUserMapper")
public class CUserServiceImpl extends ServiceImpl<CUserMapper, CUser> implements CUserService {

    @Autowired
    private CUserDetailService userDetailService;

    /**
     * @Author 李昂
     * @Description 注册用户  @CachePut每增加一个用户进行缓存
     * @Date 2020/12/2 21:34
     */

    @Override
    @CacheEvict(value = "change", allEntries = true)
    public boolean register(CUser user) throws Exception {
        if (user != null) {
            CUser cu = getUserBySno(user.getSno());
            if (cu != null) {
                throw new Exception("这个用户已经存在，不能重复。");
            } else {
                //存入数据库
                return this.save(voTopo(user));
            }
        } else {
            throw new Exception("错误消息：用户对象为空！");
        }
    }


    /**
     * @Author 李昂
     * @Description 从数据库中根据学号查询用户是否存在
     * @Date 2020/12/2 20:37
     */
    @Override
    @Cacheable(value = "change")
    public CUser getUserBySno(String sno) {
        return this.baseMapper.getIUserBySon(sno);
    }

    /**
     * @Author 李昂
     * @Description 查询所有用户
     * @Date 2020/12/3 18:30
     */
    @Override
    @Cacheable(value = "change")
    public List<CUser> allUsers() {
        return this.baseMapper.allUsers();
    }


    /**
     * @Author 李昂
     * @Description 修改个人信息 allEntries = true  表示清除所有的缓存
     * @Date 2020/12/10 14:37
     */
    @Override
    @CacheEvict(value = "change", allEntries = true)
    @Transactional()
    public boolean updateAllMsg(String id, CUser user) {
        LambdaQueryWrapper<CUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CUser::getId, id);
        if (this.update(user, lambdaQueryWrapper) && userDetailService.updateUserMsg(id, user.getUserdetail())) {
            return true;
        } else {
            return false;
        }
    }

    //修改用户状态
    @Override
    @CacheEvict(value = "change", allEntries = true)
    public boolean ChangeStatue(String id, String statue) {
        return this.baseMapper.ChangeStatueById(id, statue);
    }

    @Override
    @CacheEvict(value = "change", allEntries = true)
    public boolean ChushiPwd(String id) {
        //初始密码为123456对初始密码加密
        String pwd = new BCryptPasswordEncoder().encode("123456");
        return this.baseMapper.ChushiPwd(id, pwd);
    }

    //修改用户权限
    @Override
    @CacheEvict(value = "change", allEntries = true)
    public boolean ChangeRole(String id, String role) {
        return this.baseMapper.ChangeRole(id, role);
    }

    //远程搜索
    @Override
    public List<CUser> getWeiji(String name) {
        return this.baseMapper.getWeiji(name);
    }


    //删除注册的用户  未审核通过的人
    @Override
    @CacheEvict(value = "change", allEntries = true)
    public boolean deleterRegist(String id) {
        return this.removeById(id);
    }


    //获取优秀社员的信息
    @Override
    public List<CUser> getExcellentUser() {
        return this.baseMapper.getExcellentUser();
    }

    //修改密码
    @Override
    @CacheEvict(value = "change", allEntries = true)
    public boolean modifypwd(String id, String pwd) {
        return this.baseMapper.ChushiPwd(id, new BCryptPasswordEncoder().encode(pwd));
    }

    //加载后台桌面数据
    @Override
    public CNotice getNotice() {
        return this.baseMapper.getNotice();
    }


    /**
     * @Author 李昂
     * @Description 注册uuid 和  对密码进行加密处理
     * @Date 2020/12/2 19:47
     */
    public CUser voTopo(CUser user) {
        CUser co = new CUser();
        //注册uuid
        co.setId(FunctionUtil.uuid());
        co.setClazz(user.getClazz());
        co.setNumber(user.getNumber());
        co.setStatus("0");
        co.setRole("normal");
        //对密码进行加密处理
        co.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        co.setSex(user.getSex());
        co.setName(user.getName());
        co.setSno(user.getSno());
        co.setJoinTime(FunctionUtil.formatDate(new Date()));
        return co;
    }


    /**
     * @Author 李昂
     * @Description 批量注测用户只有admin才有此权限
     * @Date 2020/12/3 12:36
     */
    @Override
    @CacheEvict(value = "change", allEntries = true)
    public boolean registers(List<CUser> user) {
        return this.saveBatch(user);
    }

    /**
     * @return
     * @Author 李昂
     * @Description 检查用户名密码是否正确
     * @Date 2020/12/3 12:36
     */
    @Override
    public CUser checklogin(String username, String password) throws Exception {
        CUser user = getUserBySno(username);

        if (user == null) {
            throw new Exception("用户名密码不正确！");
        } else {

            String status = user.getStatus();
            if (!new BCryptPasswordEncoder().matches(password, user.getPassword())) {
                throw new Exception("用户名密码不正确！");
            } else if (status.equals("0")) {
                throw new Exception("你还在审核中");
            } else if (status.equals("3")) {
                throw new Exception("你已经被锁定，请联系管理员进行解锁");
            } else {
                return user;
            }

        }
    }

}
